/*
 * Copyright (c) 2013-2015 Charkey. All rights reserved.
 *
 * This software is the confidential and proprietary information of Charkey.
 * You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the agreements you entered into with Charkey.
 *
 * Charkey MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
 *
 * Charkey SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

package cn.simastudio.talos.common.utils.hmac;

import cn.simastudio.talos.common.authc.hmac.HmacAuthRequest;
import cn.simastudio.talos.common.utils.codec.HmacSHA256Utils;

import java.util.HashMap;
import java.util.Map;

/**
 * Usage:
 *
 * @author Charkey
 * @date 2015/5/19 11:04
 */
public class HmacAuthUtils {

    public static Map<String, String> decodeClientAuthenticationHeader(String authenticationHeader) {
        if (authenticationHeader == null || "".equals(authenticationHeader)) {
            return null;
        }
        authenticationHeader = authenticationHeader.substring(4, authenticationHeader.length());
        String[] tokens = authenticationHeader.split(",");
        Map<String, String> macMap = new HashMap<>();
        for (String token : tokens) {
            String[] keyValue = token.split("=");
            macMap.put(keyValue[0], keyValue[1]);
        }
        return macMap;
    }

    public static boolean validate(HmacAuthRequest authRequest) {
        String requestUri = authRequest.getRequest().getRequestURI() + "?" + authRequest.getRequest().getQueryString();
        // 服务端和客户端约定的密钥
        String secretKey = "AUTH_SECRET_KEY";// Sima: if want to use this, confi this value in configurationData
        String uuid = authRequest.getId();
        String nonce = authRequest.getNonce();
        String digestToValidate = HmacSHA256Utils.digest(secretKey, (nonce + "\n" + requestUri + "\n" + secretKey + "\n" + uuid + "\n"));
        return digestToValidate.equals(authRequest.getMac());
    }

}
